package br.com.cast.syscast.persistencia;

import java.util.Iterator;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Component;

import br.com.cast.syscast.models.Pais;
import br.com.cast.syscast.models.Uf;

@Component 
public class UfDAO extends DAOBase {
	
	public UfDAO() {
	}
	
	public Iterator<Uf> consultaPaginada(long inicio, long total) {
		
		StringBuilder hql = new StringBuilder();
		
		hql.append("SELECT u ")
		   .append("FROM Uf u ")
		   .append(" join u.pais p ");
		
		Query query = getEntityManager()
				.createQuery(hql.toString());
		
		query.setFirstResult((int) inicio);
		query.setMaxResults((int) total);
		
		return query.getResultList().iterator();
	}
	
	public long total() {
		StringBuilder hql = new StringBuilder();
		
		hql.append("SELECT COUNT(*) as total ")
		   .append("FROM Uf");
		
		Query query = getEntityManager()
				.createQuery(hql.toString());

		return (long) query.getSingleResult();
	}
	
	public void salvar(Uf uf) {
		getEntityManager().persist(uf);
	}
	
	public void alterar(Uf uf) {
		getEntityManager().merge(uf);
	}
	
	public void excluir(Uf uf) {
		uf = (Uf) getHibernateCurrentSession()
				.get(Uf.class, uf.getId());
			getEntityManager().remove(uf);
	}

	public boolean ufJaCadastrada(Uf uf) {
		
		StringBuilder hql = new StringBuilder();
		
		hql.append("SELECT COUNT(*) as qtd ")
		   .append("FROM Uf u ")
		   .append(" join u.pais p ")
		   .append("WHERE u.sigla = :sigla ")
		   .append("AND p.id = :idPais ");
		
		if (uf.getId() != null) {//alteração
			hql.append(" AND u.id <> :id ");
		}

		Query query = getEntityManager()
				.createQuery(hql.toString());
			
		query.setParameter("sigla", uf.getSigla());
		query.setParameter("idPais", uf.getPais().getId());
		
		if (uf.getId() != null) {//alteração
			query.setParameter("id", uf.getId());
		}
		
		return (long)query.getSingleResult() > 0;

	}

	public List<Uf> consultaPorPais(Pais pais) {
		
		StringBuilder hql = new StringBuilder();
		
		hql.append(" SELECT u")
			.append(" FROM Uf u ")
			.append("   join u.pais p ")
			.append(" WHERE p.id = :id ");
		
		Query query = getEntityManager()
				.createQuery(hql.toString());
		
		query.setParameter("id", pais.getId());
		
		return query.getResultList();
	}
	
}
